package DoExercise.HSP_ZCY.A016_动态规划;

/**
 * 多样本位置全对应的尝试模型
 */
public class Code04_两个字符串的最长公共子序列
{
    public static void main(String[] args)
    {
        String str1 = "abcxqedfss";
        String str2 = "esdadeefss";
        System.out.println(commonStr(str1.toCharArray(), str2.toCharArray()));
    }
    
    
    /**
     * 四种情况
     * dp[i - 1][j - 1]     a123b VS c123f
     * dp[i - 1][j]         a123b VS cf123
     * dp[i][j - 1]         ba123 VS c123f
     * str1[i] == str2[j]  dp[i - 1][j - 1] + 1  a12b3 VS cf123
     *
     * @param str1
     * @param str2
     * @return
     */
    public static int commonStr(char[] str1, char[] str2)
    {
        int[][] dp = new int[str1.length][str2.length];
        dp[0][0] = str1[0] == str2[0] ? 1 : 0;
        for (int i = 1; i < str1.length; i++)
        {
            dp[i][0] = Math.max(dp[i - 1][0], str1[i] == str2[0] ? 1 : 0);
        }
        for (int j = 1; j < str2.length; j++)
        {
            dp[0][j] = Math.max(dp[0][j - 1], str1[0] == str2[j] ? 1 : 0);
        }
        
        for (int i = 1; i < str1.length; i++)
        {
            for (int j = 1; j < str2.length; j++)
            {
                dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
                if (str1[i] == str2[j])
                {
                    dp[i][j] = Math.max(dp[i][j], dp[i - 1][j - 1] + 1);
                }
            }
        }
        return dp[str1.length - 1][str2.length - 1];
    }
}
